package com.addzero.web.ui.hooks.form

import androidx.compose.foundation.layout.*
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.addzero.web.ui.hooks.UseHook
import com.addzero.web.ui.hooks.table.entity.IColumn

class UseDynamicForm<E : Any>(
    private val columns: List<IColumn<E>> ,
    /** * 几栏显示 */
    private val columnCount: Int = 2,
) : UseHook<UseDynamicForm<E>> {


    var formItem by mutableStateOf(null as E?)

    // 表单验证错误信息
    private var validationErrors by mutableStateOf(mutableStateMapOf<String, String>())

    // 按钮区域可见性
    var showButtons by mutableStateOf(true)

    // 表单按钮点击回调
    var onSubmit: ((E) -> Unit)? = null
    var onCancel: (() -> Unit)? = null

    /**
     * 更新表单项，优化重组逻辑
     */
    fun updateFormItem(newItem: E?) {
        formItem = null
        formItem = newItem
    }

    fun validate(): Boolean {
        validationErrors.clear()
        columns.forEach { column ->
            if (!column.validator(formItem!!)) {
                validationErrors[column.title] = column.errorMessage
            }
        }
        return validationErrors.isEmpty()
    }

    override val render: @Composable () -> Unit
        get() = {
            val useDynamicForm = this.rememberState()

            Column(modifier = Modifier.fillMaxWidth()) {
                // 表单主体内容
                MultiColumnContainer(
                    columnCount = columnCount,
                    size = columns.size,
                    horizontalSpacing = 16,
                    verticalSpacing = 8
                ) { index ->
                    FormItem(columns[index], useDynamicForm, formItem)
                }

                // 按钮区域
                if (showButtons) {
                    Spacer(modifier = Modifier.height(16.dp))

                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.End,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        OutlinedButton(
                            onClick = { onCancel?.invoke() },
                            modifier = Modifier.padding(end = 8.dp)
                        ) {
                            Text("取消")
                        }

                        Button(
                            onClick = {
                                if (validate() && formItem != null) {
                                    onSubmit?.invoke(formItem!!)
                                }
                            }
                        ) {
                            Text("提交")
                        }
                    }
                }
            }
        }
}

